package com.example.demo2.util;

import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBC_Demo {
    // 加载mysql5数据库驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
    }

    //连接数据库
    public static java.sql.Connection getConnection(){
        try {
            //jdbc:mysql://localhost:3306/mybatis
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis","root","123456");
        }catch (SQLException e){
            e.printStackTrace();
        }
        return null;
    }

    // 得到sql查询语句对象
    public static java.sql.Statement getStatement(){
        try {
            return getConnection().createStatement();
        }catch (SQLException e){
            e.printStackTrace();
        }
        return null;
    }

    //查询user表数据
    public static void main(String[] args) {
        try {
            java.sql.Statement statement = getStatement();
            java.sql.ResultSet resultSet = statement.executeQuery("select * from emp");
            // 遍历结果集 输出
            while (resultSet.next()){
                System.out.println(resultSet.getString("username"));
                System.out.println(resultSet.getString("password"));
            }

            //释放
            resultSet.close();
        }
        catch (SQLException e){
            e.printStackTrace();
        }
    }
}
